package org.future.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class RefactPackage {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("...start...");
        String base = "D:/eclipse_Aplpha/workspace/Axis_Develop/modules";
        String suffix = "apache" + File.separator + "axis2";
        String newSuffix = "loushang" + File.separator + "ws";
        // 
        RefactPackage t = new RefactPackage();
        t.setSuffix(suffix);
        List<String> list = t.getFolders(base);
        for(int i=0;i<list.size();i++){
            String val = list.get(i);
            String newDir = val.replace(suffix, newSuffix);
            File oldFile = new File(val);
            File newFile = new File(newDir);
            newFile.getParentFile().mkdirs();              // 创建新目录
            boolean result = oldFile.renameTo(newFile);    // 重命名
            System.out.println((i+1) + ": " + newFile.getAbsolutePath() + " " + result);
            oldFile.getParentFile().delete();              // 删除旧目录
        }
        System.out.println("size:"+list.size());
    }
    // 起始目录
    private String base;
    // 结束后缀
    private String suffix;
    
    public String getBase() {
        return base;
    }
    public void setBase(String base) {
        this.base = base;
    }
    public String getSuffix() {
        return suffix;
    }
    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
    /**
     * 
     * @param base
     * @return
     */
    public List<String> getFolders(String base){
        List<String> list = new ArrayList<String>();
        File file = new File(base);
        findFolders(file, 0, 5, list);           // 此处的 level = 5 需根据具体情况调整
        return list;
    }
    /**
     * 查找符合条件的所有文件夹
     * @param dir    : 当前目录
     * @param level  : 当前层数
     * @param maxDeep: 最大深度
     */
    private void findFolders(
            File file,
            int level,int maxDeep,List<String> list){
        if(!file.isDirectory()){                  // 不是目录
            return;
        }
        if(level == maxDeep){                     // 到达预定深度
            String dir = file.getAbsolutePath();
            if(dir.endsWith(getSuffix())){
                list.add(dir);                    // 存储合法路径
            }
            return;                               // 结束递归
        }else if(level < maxDeep){
            File[] fs = file.listFiles();            
            for(File f : fs){                     // 递归目录
                if(f.isDirectory()){
                    findFolders(f,level+1,maxDeep,list);
                }
            }
        } 
    }// end findFolders
}
